<?php
	require_once '../../../const.php';
	require_once '../database/mysql/MysqlUserDao.php';
	require_once '../domain/User.php';
	require_once '../fragment/language.php';
	
	use org\kahikai\database\mysql\MysqlUserDao;
	use org\kahikai\domain\User;
	
	session_start();
	if(!isset($_SESSION['userDao'])) {
		$_SESSION['userDao'] = new MysqlUserDao();
	}
	
	$text = getLocalizedText('create_account');
	
	$user = new User(null, '', '', '', 'user', '', '');
	
	$_SESSION['create_user_errors'] = array();
	
	if(isset($_REQUEST['last_name']) && $_REQUEST['last_name'] != '') {
		$user->lastName = $_REQUEST['last_name'];
	} else {
		array_push($_SESSION['create_user_errors'], 'last_name');
	}
	
	if(isset($_REQUEST['first_name']) && $_REQUEST['first_name'] != '') {
		$user->firstName = $_REQUEST['first_name'];
	} else {
		array_push($_SESSION['create_user_errors'], 'first_name');
	}
	
	if(isset($_REQUEST['email']) && $_REQUEST['email'] != '') {
			$user->email = $_REQUEST['email'];
		$existingUser = $_SESSION['userDao']->getByEmail($_REQUEST['email']);
		if(isset($existingUser)) {
			array_push($_SESSION['create_user_errors'], 'exists');
		}
	} else {
		array_push($_SESSION['create_user_errors'], 'email');
	}
	
	if(!isset($_REQUEST['email_conf']) || $_REQUEST['email_conf'] != $user->email) {
		array_push($_SESSION['create_user_errors'], 'email_conf');
	}
	
	if(isset($_REQUEST['password']) && $_REQUEST['password'] != '') {
		$user->password = md5($_REQUEST['password']);
	} else {
		array_push($_SESSION['create_user_errors'], 'password');
	}
	
	if(!isset($_REQUEST['password_conf']) || md5($_REQUEST['password_conf']) != $user->password) {
		array_push($_SESSION['create_user_errors'], 'password_conf');
	}
	$user->confirmationNumber = rand(0, 1000000);
	$_SESSION['user'] = $user;
	
	$userId = NULL;
	if(count($_SESSION['create_user_errors']) == 0) {
		$userId = $_SESSION['userDao']->saveUser($user);
	}
	if($userId != NULL) {
		$user->id = $userId;
		$confUrl = "http://localhost/kahikai/org/kahikai/action/confirm_account.php?id=$user->id&confirmation_number=$user->confirmationNumber";
		
		$msg = "<html><body><p>" . $text['greetings'] . " $user->firstName,</p>\n";
		$msg.= "<p>" . $text['welcome'] . "<br>\n";
		$msg.= $text['clic'] . "<br>\n";
		$msg.= "<a href=\"$confUrl\">$confUrl</a></p>\n";
		$msg.= "<p>" . $text['regards'] . "<br>\n";
		$msg.= $text['webmaster'] . "</p></body></html>\n";
		
		$headers = "FROM: kahikai admin admin@kahikai.org\n";
		$headers.= "MIME-Version: 1.0\n";
		$headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
		
		mail($user->email, $text['subject'], $msg, $headers);
		
		header("location: $ROOT_URL/kahikai");
	} else {
	 	$source = $_SERVER['HTTP_REFERER'];
	 	header("location: $source");
	}
?>